$(function () {
  let id;
  // 查询参数
  let o = {
    type: '',
    article_id: id,
    action: '',
  };

  getUrlData();
  homePage();
  getRenderHot();
  getNavSkip();
  lovenum();
  getSkip();
  userCenter();

  // 首页和全局数据
  function homePage() {
    axios({
      method: 'GET',
      url: '/index/index',
    }).then(function (res) {
      // console.log(res);
      // 导航栏;
      let strNav = res.data.data.allCate
        .map(item => {
          return `
      <li class="menu-item menu-item-type-taxonomy menu-item-object-category">
          <a href="list.html" id=${item.id}><span class="fa fa-bullhorn iconfont ${item.icon}"></span>${item.catename}</a>
      </li>  `;
        })
        .join('');
      $('#nav').append(strNav);
      // 右侧广告位
      let advStr = res.data.data.sideBanner
        .map(item => {
          return `
            <a href=${item.advimglink} rel="nofollow" target="_blank" title=${item.advimgdesc}>
            <img class="g430" style="width:360px;height:133px;" src="http://124.223.14.236:8060/${item.advimgsrc}" alt=${item.advimgdesc}>
            </a>
            `;
        })
        .join('');
      $('.textwidget').html(advStr);
      // 热门标签
      let allTag = res.data.data.allTag
        .map(item => {
          return `
            <li><a title="" href="">${item.tagname}</a></li>
            `;
        })
        .join('');
      $('.widget_tags_inner').html(allTag);
      // 友情链接
      let allLink = res.data.data.allLink
        .map(item => {
          return `
            <li>
                <a href=${item.url}>
                    <img src="http://124.223.14.236:8060/${item.img}" alt="">
                    <p>${item.des}</p>
                </a>
            </li>
            `;
        })
        .join('');
      $('.widget_comments ul').html(allLink);
      // 底部友情链接
      let footerLink = res.data.data.allLink
        .map(item => {
          return `<a href=${item.url} title="百度">${item.des}</a> <span>|</span>`;
        })
        .join('');
      $('.footer .link').append(footerLink);
    });
  }
  //热门文章
  function getRenderHot() {
    axios({
      method: 'GET',
      url: '/index/recommend',
    }).then(function (res) {
      // console.log(res);
      let str = res.data.data.list
        .map(item => {
          return `
            <li>
                <a target="_blank" href="" id=${item.id}>
                    <span class="thumbnail">
                        <img src="http://124.223.14.236:8060/${item.pic}" class="thumb" />
                    </span>
                    <span class="text">${item.title}</span>
                    <span class="text-muted post-views">阅读(${item.click})</span>
                </a>
          </li> `;
        })
        .join('');
      $('.items-02').html(str);
    });
  }
  // 渲染文章详情
  function gerRenderArticle(id) {
    axios({
      method: 'GET',
      url: '/index/show',
      params: {
        id: id,
      },
      headers: {
        token: localStorage.getItem('token'),
      },
    }).then(function (res) {
      console.log(res);
      // 渲染面包屑
      $('#currentPosition').html(res.data.data.info.catename);
      $('.article-title').html(res.data.data.info.title);
      // 渲染标题描述
      let articleMeta = `
                <li>
                    <a href="">悦享·编辑</a> 发布于 ${time(res.data.data.info.create_date)}
                </li>
                <li>分类：<a href="" rel="category tag">${res.data.data.info.catename}</a></li>
                <li>
                    <span class="post-views">阅读(${res.data.data.info.click})</span>
                </li>
                <li> <a href="javascript:;" data-type="1" class="post-like" data-isCollect=${res.data.data.info.isCollect} data-article_id="${res.data.data.info.cateid}">${collect(res.data.data.info.isCollect)}</a></li>`;
      $('.article-meta').html(articleMeta);
      // 渲染文章内容
      $('.article-content').html(res.data.data.info.content);
      // 渲染点赞
      let articlesocial = `
            <a href="javascript:;" class="action action-like post-like" " data-type="2" data-isLike=${res.data.data.info.isLike} style=${like(res.data.data.info.isLike)}>
                <i class="glyphicon glyphicon-thumbs-up"></i>赞 (<span id="isLike">${res.data.data.info.lovenum}</span>)
            </a> `;
      $('.article-social').html(articlesocial);
      // 渲染标签信息
      $('.article-tags a').html(res.data.data.info.keywords);
      // 渲染上一篇和下一篇
      let articleNav = `
                <span class="article-nav-prev">
                <span>上一篇</span>
                <a href="" rel="prev" id=${res.data.data.next[0].id}>${res.data.data.next[0].title}</a>
                </span>
                <span class="article-nav-next">
                <span>下一篇</span>
                <a href="" rel="next" id=${res.data.data.prev[0].id}>${res.data.data.prev[0].title}</a>
                </span>
            `;
      $('.article-nav').html(articleNav);
      // 渲染推荐文章
      let str = res.data.data.recommend.map(item => {
        return `
                <li>
                <a href="javascript:;" id=${item.id}>
                  <span>
                    <img src="http://124.223.14.236:8060/${item.pic}" class="thumb" />
                  </span>
                  ${item.title}
                </a>
              </li>
                `;
      });
      $('.relates ul').html(str);
    });
  }
  // 用户中心和退出
  function userCenter() {
    // 没有token的时候隐藏用户中心和退出
    if (localStorage.getItem('token')) {
      let str = `
       <a href="user.html" id="user"><i class="fa fa-user"></i>&nbsp;用户中心</a>
       <a href="javascript:;" class="quit"><i></i>&nbsp;退出</a>`;
      $('.slinks').html(str);
    } else {
      let str = `
        <a href="login.html"><i class="fa fa-hand-o-right"></i>&nbsp;登录</a> |
        <a href="reg.html"><i class="fa fa-registered"></i>&nbsp;注册</a>`;
      $('.slinks').html(str);
    }
    $('#user').on('click', function (e) {
      e.preventDefault();
      if (localStorage.getItem('token')) {
        location.href = 'user.html';
      } else {
        location.href = 'login.html';
      }
    });
    $('.quit').on('click', function (e) {
      layer.confirm('你确定要退出吗?', { icon: 3, title: '退出提示' }, function (index) {
        localStorage.removeItem('token');
        location.reload();

        layer.close(index);
      });
    });
  }
  // 点赞和收藏
  function lovenum() {
    $('.article-meta,.article-social').on('click', '.post-like', function (e) {
      e.preventDefault();
      o.type = $(this).attr('data-type');
      if (o.type === '1') {
        let a = $(this).attr('data-isCollect') == 'true' ? true : false;
        // 获取是否收藏
        if (a) {
          o.action = 'del';
        } else {
          o.action = 'add';
        }
      }
      if (o.type === '2') {
        // 获取是否点赞
        let b = $(this).attr('data-isLike') == 'true' ? true : false;
        if (b) {
          o.action = 'del';
        } else {
          o.action = 'add';
        }
      }
      axios({
        method: 'GET',
        url: '/user/userDataHandle',
        params: o,
        headers: {
          token: localStorage.getItem('token'),
        },
      }).then(function (res) {
        // console.log(res);
        gerRenderArticle(id);
        o.action = '';
        o.type = '';
      });
      if ($('.action-like').attr('data-isLike') == 'true') {
        console.log(11);
        $('#isLike').text(Number($('#isLike').text()) + 1);
      } else {
        console.log(22);
        $('#isLike').text(Number($('#isLike').text()) + -1);
      }
    });
  }
  // 导航栏跳转
  function getNavSkip() {
    $('#nav').on('click', 'a', function (e) {
      e.preventDefault();
      window.open('list.html?id=' + $(this).attr('id'));
    });
  }
  // 获取url携带来的的数据,进入页面时渲染特定页面
  function getUrlData() {
    let url = location.href;
    url = url.split('?')[1];
    const urlSearchParams = new URLSearchParams(url);
    const params = Object.fromEntries(urlSearchParams.entries());
    id = params.id;
    o.article_id = params.id;
    gerRenderArticle(id);
  }
  // 点击跳转详情页
  function getSkip() {
    $('#recommend,.items-02,.article-nav').on('click', 'a', function (e) {
      e.preventDefault();
      location.replace('show.html?id=' + $(this).attr('id'));
    });
  }
  // 时间函数
  function time(mesc) {
    let now = new Date(mesc);
    let year = getZero(now.getFullYear());
    let month = getZero(now.getMonth() + 1);
    let day = getZero(now.getDate());
    return year + '-' + month + '-' + day;
  }
  // 时间补零函数
  function getZero(num) {
    return num < 10 ? '0' + num : num;
  }
  // 定义收藏方法
  function collect(boo) {
    if (boo) {
      return '已收藏';
    } else {
      return '点击收藏';
    }
  }
  //定义点赞方法
  function like(like) {
    if (like) {
      return 'background-color:#ff6e64';
    } else {
      return 'background-color:#e3e3e3';
    }
  }
});
